import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { computed, defineComponent, PropType, VNode } from 'vue';
import {
  IDEToolbar,
  IDEToolbarItem,
  IDETBGroupItem,
  IDETBUIActionItem,
} from '@ibiz/model-core';
import { IExtraButton } from '@ibiz-template/runtime';
import { ToolbarController } from './toolbar.controllerr';
import { IBizExportExcel } from './export-excel/export-excel';
import './toolbar.scss';

const btnContent = (item: IDEToolbarItem): (string | VNode)[] => {
  const image = item.sysImage;
  const result = [];
  if (item.showIcon && image) {
    result.push(<iBizIcon icon={image} />);
  }
  if (item.showCaption && item.caption) {
    result.push(item.caption);
  }
  return result;
};

export const ToolbarControl = defineComponent({
  name: 'IBizToolbarControl',
  props: {
    modelData: {
      type: Object as PropType<IDEToolbar>,
      required: true,
    },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
  },
  setup() {
    const c = useControlController((...args) => new ToolbarController(...args));
    const ns = useNamespace(`control-${c.model.controlType!.toLowerCase()}`);

    const btnSize = computed(() => {
      return c.state.viewMode === 'EMBED' ? 'small' : 'default';
    });

    // 点击事件
    const handleClick = async (
      item: IDEToolbarItem,
      event: MouseEvent,
      params?: IData,
    ): Promise<void> => {
      await c.onItemClick(item, event, params);
    };

    const renderExtraButtons = (extraButtons: IExtraButton[]): VNode[] => {
      return extraButtons.map(button => {
        return (
          <el-button
            title={button.tooltip}
            size={btnSize.value}
            onClick={(e: MouseEvent): Promise<void> => handleClick(button, e)}
          >
            {btnContent(button)}
          </el-button>
        );
      });
    };

    const renderToolbarItem = (item: IDEToolbarItem): VNode | null => {
      const itemId = item.id!;
      if (item.itemType === 'SEPERATOR') {
        return (
          <div key={itemId} class={[ns.e('item'), ns.e('item-separator')]}>
            |
          </div>
        );
      }
      if (item.itemType === 'RAWITEM') {
        return (
          <div key={itemId} class={[ns.e('item'), ns.e('item-rawitem')]}>
            {btnContent(item)}
          </div>
        );
      }
      if (
        item.itemType === 'DEUIACTION' &&
        c.state.buttonsState[itemId].visible
      ) {
        const actionId = (item as IDETBUIActionItem).uiactionId;
        if (actionId === 'exportexcel') {
          return (
            <IBizExportExcel
              item={item}
              btnContent={btnContent}
              size={btnSize.value}
              controller={c}
              onExportExcel={(e: MouseEvent, data: IData): void => {
                handleClick(item, e, data);
              }}
            ></IBizExportExcel>
          );
        }
        return (
          <div key={itemId} class={[ns.e('item'), ns.e('item-deuiaction')]}>
            <el-button
              title={item.tooltip}
              size={btnSize.value}
              loading={c.state.buttonsState[itemId].loading}
              disabled={c.state.buttonsState[itemId].disabled}
              onClick={(e: MouseEvent): Promise<void> => handleClick(item, e)}
            >
              {btnContent(item)}
            </el-button>
          </div>
        );
      }
      if (item.itemType === 'ITEMS') {
        return (
          <div key={itemId} class={[ns.e('item'), ns.e('item-items')]}>
            <el-dropdown trigger='click' placement='bottom-start'>
              {{
                default: (): VNode => {
                  return (
                    <el-button title={item.tooltip} size={btnSize.value}>
                      {btnContent(item)}
                    </el-button>
                  );
                },
                dropdown: (): VNode => {
                  return (
                    <el-dropdown-menu>
                      {(item as IDETBGroupItem).detoolbarItems?.map(item2 => {
                        return (
                          <el-dropdown-item
                            key={item2.id}
                            onClick={(e: MouseEvent): Promise<void> =>
                              handleClick(item2, e)
                            }
                          >
                            {btnContent(item2)}
                          </el-dropdown-item>
                        );
                      })}
                    </el-dropdown-menu>
                  );
                },
              }}
            </el-dropdown>
          </div>
        );
      }
      return null;
    };

    return {
      c,
      btnSize,
      ns,
      handleClick,
      renderExtraButtons,
      renderToolbarItem,
    };
  },
  render() {
    const { state } = this.c;

    return (
      <iBizControlBase
        controller={this.c}
        class={[this.ns.m(state.viewMode.toLowerCase())]}
      >
        {/*  绘制最前方的额外按钮 */}
        {state.extraButtons.before?.length &&
          this.renderExtraButtons(state.extraButtons.before)}
        {this.modelData.detoolbarItems?.map((item, index) => {
          const toolbarItemNode = this.renderToolbarItem(item);
          // 绘制指定位置后的额外按钮
          if (state.extraButtons[index]?.length) {
            return [
              toolbarItemNode,
              this.renderExtraButtons(state.extraButtons[index]),
            ];
          }
          return toolbarItemNode;
        })}
        {/* 绘制最后方的额外按钮 */}
        {state.extraButtons.after?.length &&
          this.renderExtraButtons(state.extraButtons.after)}
      </iBizControlBase>
    );
  },
});
